<?php
/**
 * @Author: rocky
 * @Copyright: 广州拓冠科技 <http://my8m.com>
 * Date: 2019/8/28
 * Time: 17:54
 */


namespace app\shop\controller\api\v1;



use app\common\controller\BaseApiController;
use app\common\facade\Token;
use app\shop\model\ShopCart;
use app\shop\model\ShopGoodsSpec;
use app\shop\resource\CartResoure;
use app\shop\validate\CartValidate;

/**
 * 购物车
 * Class Cart
 * @package app\shop\controller\api\v1
 */
class Cart extends BaseApiController
{
    //获取购物车列表
    public function getInfo(){
        $store_id = $this->request->get('store_id');
        // halt($store_id);
        $data = ShopCart::uid()->where('store_id',$store_id)->with(['goods'])->select();
        if($store_id){
            $this->successCode(CartResoure::collection($data));
        }else{
            $this->errorCode(100,'附近3公里无门店');
        }
    }
     //添加商品到购物车
    public function postInfo()
    {
        $data = (new CartValidate())->goCheck();
        $where['good_id'] = $data['good_id'];
        $where['store_id'] = $data['store_id'];
        $cart = ShopCart::uid()->where($where)->find();
        if ($cart) {
            if ($data['type']) {
                $cart->setInc('num', $data['num']);
            }else{
                $cart->setDec('num', $data['num']);
                if ($cart->num == 0) {
                    $cart->delete();
                }
            }
        } else {
            $data['uid'] = Token::id();
            ShopCart::create($data);
        }
        $this->successCode();
    }
    //购车修改
    public function putInfo()
    {
        $id = $this->request->put('cart_id');
        $store_id = $this->request->put('store_id');
        $num = $this->request->put('num');
        ShopCart::uid()->where('id', $id)->where('store_id', $store_id)->update([
            'num' => $num,
        ]);
        if (!$num) {
            ShopCart::uid()->where('id',$id)->delete();
        }
        $this->successCode();
    }
    //删除
    public function deleteInfo(){
        $id = $this->request->delete('cart_id');
        ShopCart::uid()->where('id', $id)->delete();
        $this->successCode();
    }
    //清空
    public function deleteAll(){
        ShopCart::uid()->delete();
        $this->successCode();
    }
}